package com.dhh.sky.activity;

import org.json.JSONObject;
import com.dhh.sky.R;
import com.dhh.sky.SDAApplication;
import com.dhh.sky.identity.User;
import com.dhh.sky.util.JsonKeys;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationException;
import com.microsoft.live.LiveOperationListener;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

public class HomeActivity extends Activity implements View.OnClickListener{
	private TextView mNameTextView; 
	
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        
        this.findViewById(R.id.h_go).setOnClickListener(this);
        mNameTextView = (TextView)findViewById(R.id.hello);
	}
	
	@Override
	public void onStart(){
		super.onStart();
		initData();
	}
	
	@Override
	public void onClick(View v) {
		Intent intent = new Intent(HomeActivity.this,FileListActivity.class);
		this.startActivity(intent);
	}
	
	private void initData(){
		LiveConnectClient connectClient = ((SDAApplication)getApplication()).getConnectClient();
        connectClient.getAsync("me", new LiveOperationListener() {
            @Override
            public void onError(LiveOperationException exception, LiveOperation operation) {
                showToast(exception.getMessage());
            }

            @Override
            public void onComplete(LiveOperation operation) {
                JSONObject result = operation.getResult();

                if (result.has(JsonKeys.ERROR)) {
                    JSONObject error = result.optJSONObject(JsonKeys.ERROR);
                    String code = error.optString(JsonKeys.CODE);
                    String message = error.optString(JsonKeys.MESSAGE);

                    showToast(code + ": " + message);
                } else {
                    User user = new User(result);
                    mNameTextView.setText("Hello, " + user.getName() + "!");
                }
            }
        });
	}
	
	private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }

}
